package net.sourceforge.peers.sdp;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.util.Hashtable;
import java.util.List;

/**
 * MediaDescription 通常对应一个音频流或一个视频流（peer 不支持视频，但理论上它的 sdp 堆栈可以支持它）
 * MediaDestination包含IP地址、端口和编解码器的组合
 * @author Mr.Yan
 */
public class MediaDescription {

    private String type;
    private InetAddress ipAddress;
    // attributes not codec-related
    private Hashtable<String, String> attributes;
    private int port;
    private List<Codec> codecs;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Hashtable<String, String> getAttributes() {
        return attributes;
    }

    public void setAttributes(Hashtable<String, String> attributes) {
        this.attributes = attributes;
    }

    public InetAddress getIpAddress() {
        return ipAddress;
    }

    public void setIpAddress(InetAddress ipAddress) {
        this.ipAddress = ipAddress;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public List<Codec> getCodecs() {
        return codecs;
    }

    public void setCodecs(List<Codec> codecs) {
        this.codecs = codecs;
    }

    @Override
    public String toString() {
        StringBuilder buf = new StringBuilder();
        buf.append(RFC4566.TYPE_MEDIA).append(RFC4566.SEPARATOR);
        buf.append(type).append(" ").append(port);
        buf.append(" RTP/AVP");
        for (Codec codec: codecs) {
            buf.append(" ");
            buf.append(codec.getPayloadType());
        }
        buf.append("\r\n");
        if (ipAddress != null) {
            int ipVersion;
            if (ipAddress instanceof Inet4Address) {
                ipVersion = 4;
            } else if (ipAddress instanceof Inet6Address) {
                ipVersion = 6;
            } else {
                throw new RuntimeException("unknown ip version: " + ipAddress);
            }
            buf.append(RFC4566.TYPE_CONNECTION).append(RFC4566.SEPARATOR);
            buf.append("IN IP").append(ipVersion).append(" ");
            buf.append(ipAddress.getHostAddress()).append("\r\n");
        }
        for (Codec codec: codecs) {
            buf.append(codec.toString());
        }
        if (attributes != null) {
            for (String attributeName: attributes.keySet()) {
                buf.append(RFC4566.TYPE_ATTRIBUTE).append(RFC4566.SEPARATOR);
                buf.append(attributeName);
                String attributeValue = attributes.get(attributeName);
                if (attributeValue != null && !"".equals(attributeValue.trim())) {
                    buf.append(":").append(attributeValue);
                }
                buf.append("\r\n");
            }
        }
        return buf.toString();
    }

}
